﻿using System.Linq;
using Accona.Monitoring.AppStatistics;
using Accona.Monitoring.Exposure.REST;
using Accona.Monitoring.Publishers;

namespace Accona.Monitoring
{
    public class Monitor : MonitorConfigurationBase
    {
        internal readonly MonitorConfig _config = new MonitorConfig();
        internal static Monitor _instance;

        private Monitor()
        {
            _monitor = this;
        }

        public static Monitor Setup()
        {
            return _instance ?? (_instance = new Monitor());
        }

        public static void Publish(IAppStatistics appStatistics)
        {
            foreach (var publisher in _instance._config.Publishers)
            {
                publisher.Publish(
                        new AppStatisticsEvent(
                            AppStatisticsEventType.Broadcast,
                            appStatistics
                        )
                );
            }
        }

        public static void One(string appName, string @namespace, string tag)
        {
            Increment(appName, @namespace, tag);
        }

        public static void Increment(string appName, string @namespace, string tag, int? count = null)
        {
            foreach (var publisher in _instance._config.Publishers)
            {
                publisher.Publish(new AppStatisticsEvent(
                                      AppStatisticsEventType.Increment,
                                      new DefaultAppStatistics()
                                      {
                                          AppName = appName,
                                          StatNamespace = @namespace,
                                          Tag = tag,
                                          Value = count == null ? 1 : count.Value
                                      }));
            }
        }

        public static T GetPublisher<T>() where T : IPublisher
        {
            var item =  Monitor._instance._config.Publishers.FirstOrDefault(a => a.GetType().Equals(typeof (T)));
            return (T) item;
        }

        
    }
}
